<?php
/**
 * Api根控制器父类（）
 * Interface引用api模式，没有display等view的渲染和页面模版输出
 */
namespace Common\Controller;
use Api\Common\Common;
use Think\Controller;
// use Api\Common;

class RootController extends Controller{

    //客户端类型（允许登录类型）
    protected $client_type_array = array('android', 'wap', 'wechat', 'ios');
    //列表默认每页分页数
    protected $pageNum = 10;
    //省市区工具类
    protected $areas_common=null;
    //通用工具类
    protected $common_common=null;
    //用户信息数据
    protected $member_info = array();
    //对应表查询的字段列表
    protected $select_fields_column=array(
        'member'=>'hx_id,member_name,avatar,identification_photo,student_photo,self_photo,member_id,truename,signature,birthday,gender,coin,point,country,province,city,area,school,latest_signed_time,status',
        
        );

    public function __construct() {
        parent::__construct();

        //语言设置（暂无此配置）

        //统一验证请求参数
         $this->check_requestData();

        //初始化工具类
//        $this->areas_common=new \Api\Common\Areas();
//        $this->common_common=new \Api\Common\Common();

        //初始化模型对象

        $this->comMod =new \Api\Model\CommonModel(); //通用公共调用
        $this->tokenMod =new \Api\Model\Mb_user_tokenModel();    //手机端令牌模型
        $this->bangdanMod =new \Api\Model\SectiontopicModel();  //榜单模型
        $this->centerMod =new \Api\Model\CenterModel();         //个人中心模型
        $this->communityMod =new \Api\Model\CommunityModel();      //学生社团模型
        $this->englishMod =new \Api\Model\EnglishtopicModel();  //英语角模型
        $this->hometownMod =new \Api\Model\HometownModel();     //同乡会模型

        //全局控制器初始化
        if(method_exists($this,'_initialize')){
            $this->_initialize();
        }

        //分页数处理
        $page = intval($_REQUEST['pageNum']);
        if($page > 0) {
            $this->pageNum = $page;
        }

    }


    /*
     *------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     * 通用方法（初始化时候与数据库交互操作方法）
     *-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
    */

    //登陆生成token
    public function _get_token($member_id, $member_name, $client) {
        //重新登陆后以前的令牌失效
        //暂时停用

        //$condition = array();
        //$condition['member_id'] = $member_id;
        //$condition['client_type'] = $_POST['client'];
        //$model_mb_user_token->delMbUserToken($condition);
        
        //生成新的token
        $mb_user_token_info = array();
        $token = md5($member_name . strval(NOW_TIME) . strval(rand(0,999999)));
        $strToken = C('WKY_KEY').'|'.strtotime('+1 day'); //时间作为过期截止时间
        $token = myDes_encode($strToken, C('WKY_KEY'));
        $mb_user_token_info['member_id'] = $member_id;
        $mb_user_token_info['member_name'] = $member_name;
        $mb_user_token_info['token'] = $token;
        $mb_user_token_info['login_time'] = NOW_TIME;
        $mb_user_token_info['client_type'] = $client;

        $result = $this->tokenMod->addMbUserToken($mb_user_token_info);

        if($result) {
            return $token;
        } else {
            return '';
        }
    }



    /*
     *------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     * 通用方法（验证和json返回基本函数封装方法）
     *-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
    */

    //通用检查接口参数传递是否正确，并返回类型错误说明
    public function check_requestData(){
        $access_control=isset($GLOBALS['CheckRequestData'][CONTROLLER_NAME]) ? $GLOBALS['CheckRequestData'][CONTROLLER_NAME] : array();
        $access_function=isset($access_control[ACTION_NAME]) ? $access_control[ACTION_NAME] : array();
        $data=(empty($access_control) || empty($access_function)) ? array() : $access_function;
        if(!in_array($_REQUEST['client'], $this->client_type_array)){
            $extend_data['msg']='参数client的值不合法！';
            $this->myApiPrint('400','',$extend_data);
        }
        if(!empty($data)){
            if(!empty($_POST)){
                $this->check_postData($data);
            }else if($_GET){
                $this->check_getData($data);
            }
        }
    }

    public function check_postData($data = null){
        if(!empty($data)){
            $fields=array_keys($data);
            foreach($fields as $key=>$value){
                if((!isset($_REQUEST[$value]))||(empty($_REQUEST[$value]))){
                    $params_instruction=$data[$value]['instruction'] ? $data[$value]['instruction'] : '';
                    $extend_data = array();
                    $extend_data['msg']='参数'.$value.'的值不能为空！'.$params_instruction;
                    $this->myApiPrint('300','',$extend_data);
                }else{
                    //验证手机，邮箱格式等等
//                    if($data[$value]['data_type']=='int' && intval($_REQUEST[$value])==0){
//                        $this->myApiPrint('参数'.$value.'的值为整型且不能为0！','300');
//                    }
                }
            }
        }
    }

    /**
     * @param null $data
     * @return array|mixed|null
     * Function descript: 过滤get提交的参数；
     *
     */
    public function check_getData($data = null){
        if(!empty($data)){
            $fields=array_keys($data);
            foreach($fields as $key=>$value){
                if((!isset($_GET[$value]))||(empty($_GET[$value]))){
                    $params_instruction=$data[$value]['instruction'] ? $data[$value]['instruction'] : '';
                    $extend_data = array();
                    $extend_data['msg']='参数'.$value.'的值不能为空！'.$params_instruction;
                    $this->myApiPrint('300','',$extend_data);
                }else{
                    //验证手机，邮箱格式等等
//                    if($data[$value]['data_type']=='int' && intval($_GET[$value])==0){
//                        $this->myApiPrint('参数'.$value.'的值为整型且不能为0！','300');
//                    }
                }
            }
        }
    }

    //分页数据相关参数放回
    public function mobile_page($page_count) {
        //输出是否有下一页
        $extend_data = array();
        $current_page = intval($_REQUEST['curpage']);
        if($current_page <= 0) {
            $current_page = 1;
        }
        if($current_page >= $page_count) {
            $extend_data['hasmore'] = false;
        } else {
            $extend_data['hasmore'] = true;
        }
        $extend_data['page_total'] = $page_count;
        return $extend_data;
    }

    /**
     * 公共错误返回
     * @param $msg 需要打印的错误信息
     * @param $code 默认打印200信息
     * @param $extend_data 分页扩展数据等
     */
    public function myApiPrint($code='',$data='',$extend_data=array()){
        $code=$code ? $code : 200;
        $result['status']=($code>=100 && $code<300) ? true : false;
        $result['code']=$code;
        $result['msg']=$GLOBALS['MsgCodeData'][$code] ? $GLOBALS['MsgCodeData'][$code] : '';
        $extend_data=$extend_data ? $extend_data : array();
        $result = array_merge($result, $extend_data);
        $result['data']=$data ? $data : array();
        if($data && !is_array($data[0])){
            $result['data']=array($data);
        }
        $this->ajaxReturn($result);exit;
    }

    //登录注册时候生成的用户信息数据处理
    public function filter_member_info($data=array(),$key=''){

        $result['key']=$key ? $key : '';
        
        $result['avatar']=(isset($data['avatar']) && $data['avatar']) ? PicPath.$data['avatar'] : DEFAULT_CIRCLE_AVATAR;
        $result['member_id']=(isset($data['member_id']) && $data['member_id']) ? $data['member_id'] : 0;
        $result['member_name']=(isset($data['member_name']) && $data['member_name']) ? $data['member_name'] : '';
        $result['hx_id']=(isset($data['hx_id']) && $data['hx_id']) ? $data['hx_id'] : ''; //环信id
        $result['truename']=(isset($data['truename']) && $data['truename']) ? $data['truename'] : '';
        $result['signature']=(isset($data['signature']) && $data['signature']) ? $data['signature'] : '';
        $result['birthday']=(isset($data['birthday']) && $data['birthday']) ? $data['birthday'] : '';
        if($data['gender']){
            $result['gender']=$data['gender']==1 ? '男' : '女'; //1-男，2-女
        }else{
            $result['gender']='保密'; //0-保密
        }
        $result['coin']=(isset($data['coin']) && $data['coin']) ? $data['coin'] : 0;
        $result['point']=(isset($data['point']) && $data['point']) ? $data['point'] : 0;
        $result['country']=(isset($data['country']) && $data['country']) ? $data['country'] : '';
        $result['province']=(isset($data['province']) && $data['province']) ? $data['province'] : '';
        $result['city']=(isset($data['city']) && $data['city']) ? $data['city'] : '';
        $result['area']=(isset($data['area']) && $data['area']) ? $data['area'] : '';
        $result['identification_photo']=$data['identification_photo'];//证件照
        $result['student_photo']=$data['student_photo'];//学生证照
        $result['self_photo']=$data['self_photo'];  //个人真实形象照片

        
        $school_info=$this->getSchoolDada(unserialize($data['school']));

        $result=array_merge($result,$school_info);

        //获取用户对应等级
        $member_level_info=getMemberLevel($result['point']);
        $result['level']=$member_level_info['level'];//等级值  0，1，2，3等
        $result['level_name']=$member_level_info['name'];//等级身份，大兵，小将等
        $result['level_logo']=$member_level_info['level_logo'];//等级身份logo
        $result['coin_exchange_num_limit']=$member_level_info['coin_exchange_num_limit'];//不同等级可兑换消费的乾坤币数量限制



        return $result;
    }

    //获取学校信息
    public function getSchoolDada($data)
    {
        extract($data);
        $result['school_id']=$school_id ? $school_id : '';
        $result['name']=$name ? $name : '';
        $result['depart']=$depart ? $depart : '';
        $result['start_year']=$start_year ? $start_year : '';
        $result['classname']=$class ? $class : '';
        $result['room']=$room ? $room : '';
        $result['middle_school']=$middle_school ? $middle_school : '';
        $result['education']=$education ? $education : '';
        return $result; 
    }

    //判断是不是图片
    function isImage($filename){
        $types = '.gif|.jpeg|.png|.bmp';//定义检查的图片类型
        if(file_exists($filename)){
            $info = getimagesize($filename);
            $ext = image_type_to_extension($info['2']);
            return stripos($types,$ext);
        }else{
            return false;
        }
    }

    function is_photo_file($file)
    {
        
        $type=true;
        $photo_types='jpg|gif|png|jpeg';
        $exts=substr($file, strrpos($file, '.')+1);
        $video_arr=explode('|',$photo_types);
        if(!in_array($exts,$video_arr)){
            $type=false;
        }
        return $type;
    }
    function is_video_file($file)
    {
        $type=true;
        $video_types='flv|mp4|rmvb|avi|mpeg|ra|ram|mov|wmv';
        $exts=substr($file, strrpos($file, '.')+1);
        $video_arr=explode('|',$video_types);
        if(!in_array($exts,$video_arr)){
            $type=false;
        }
        return $type;
    }
    function is_sound_file($file)
    {
        $type=true;
        $sound_types='mp3|wav|wma|ogg|ape|acc';
        $exts=strtolower(substr($file, strrpos($file, '.')+1));
        $sound_types=explode('|',$sound_types);
        if(!in_array($exts,$sound_types)){
            $type=false;
        }
        return $type;
    }

    function is_videoOrphoto_file($file)
    {
        $type=false;
        $video_types='flv|mp4|rmvb|avi|mpeg|ra|ram|mov|wmv';
    //    $sound_types='mp3|wav|wma|ogg|ape|acc';
    //    $img_types='gif|jpg|jpeg|bmp|png';
        $exts=substr($file, strrpos($file, '.')+1);
        if(isImage($_FILES['file']['name'])!==false){
            $type=true;
        }else{
            $video_arr=explode('|',$video_types);
            if(in_array($exts,$video_arr)){
                $type=true;
            }
        }
        return $type;
    }

    //社团、同乡会状态值转描述(1-已通过、0-等待审核、-1-已被拒绝)
    public function transform_club_status($status)
    {
        $str='';
        switch ($status) {
            case 0:
                $str='等待审核'; 
                break;
            case -1:
                $str='已被拒绝'; 
                break;
            case 1:
                $str='已通过'; 
                break;
            default:
                $str=''; 
                break;
        }

        return $str;
        
    }

}